package com.hk.service.impl;

import com.hk.service.IUploadImageService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.UUID;

/**
 * @Author: zhe
 * @Date: 2021/6/17 15:22
 * @Statement: 旧式上传图片接口实现层
 */
public class UploadImageServiceImpl implements IUploadImageService {

    @Override
    public String uploadImage(String uploadPath,HttpServletRequest req, String temporary) {
        //1、创建一个解析器工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024*20); //缓冲区20K ，默认10K
        File temporaryFile = new File(temporary);
        //        判断该路径是否存在或创建
        if (!temporaryFile.exists()) {
            temporaryFile.mkdirs();
        }
        factory.setRepository(temporaryFile);
        //2、文件上传解析器
        ServletFileUpload upload = new ServletFileUpload(factory);
        //设置所有上传数据的最大值，单位字节long  10M
        upload.setSizeMax(1024*1024*10);
        //设置单个文件上传的最大值 5M
        upload.setFileSizeMax(1024*1024*5);
        // 设置字符串编码
        upload.setHeaderEncoding("UTF-8");
        //解析Request请求，将表单中每个输入项封装成一个FileItem对象
        try {
            List<FileItem> fileItemList = upload.parseRequest(req);
            for (FileItem fileItem : fileItemList) {
                //3、 判断输入的类型是 普通输入项 还是文件
                if (fileItem.isFormField()) {
                    //普通输入项 ,得到input中的name属性的值
                    String name = fileItem.getFieldName();
                    //得到输入项中的值
                    String value = fileItem.getString("UTF-8");
                    System.out.println("name=" + name + "  value=" + value);
                } else {
//                    获取文件上传字段中的文件名
                    //注意IE或FireFox中获取的文件名是不一样的，IE中是绝对路径，FireFox中只是文件名
                    String fileName = fileItem.getName();
//                    System.out.println("filiName="+fileName);
//                    防止图片名称重复
                    String substring = UUID.randomUUID().toString().replace("-", "").substring(1,8);
                    substring +="-"+fileName;
//                    4、保存上传文件到指定路径
                    try {
                        File imageFile = new File(uploadPath, substring);
                        fileItem.write(imageFile);
                        fileItem.delete(); // 删除临时文件
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return substring;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
